package org.etom.impl.ui.jobs;

import java.io.File;
import java.util.List;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.jobs.Job;
import org.etom.connector.datatypes.IMoodleModule;
import org.etom.impl.ui.Activator;
import org.etom.impl.ui.util.CommonMessages;
import org.etom.impl.ui.util.Logger;
import org.etom.impl.ui.util.ResourceManager;
import org.etom.impl.ui.wizards.WizardsMessages;

public class UploadJob extends Job {

  private List<?> resources;
  private String fileName;
  private IMoodleModule module;
  
  public UploadJob(List<?> resources, String fileName, IMoodleModule module) {
    super(CommonMessages.Upload_Progress_Name);
    this.resources = resources;
    this.fileName = fileName;
    this.module = module;
  }
  
  @Override
  protected IStatus run(IProgressMonitor monitor) {
    File tmpFile = null;
    try {
      ResourceManager resManager = Activator.getDefault().getResourceManager();
      if (null == resManager) {
        Logger.ERROR(WizardsMessages.Upload_Wizard_Page1_Res_Manager_Missing, null);
        return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
            WizardsMessages.Upload_Wizard_Page1_Res_Manager_Missing);
      }
      tmpFile = resManager.compressResources(resources, fileName);
      module.setContent(tmpFile);
      return Status.OK_STATUS;
    } catch (Exception e) {
      Logger.ERROR(WizardsMessages.Upload_Wizard_Set_Content_Fail, e);
      return new Status(IStatus.ERROR, Activator.PLUGIN_ID,
          WizardsMessages.Upload_Wizard_Set_Content_Fail);
    } finally {
      if (null != tmpFile)
        tmpFile.delete();
    }
  }

}
